package com.onlyxiahui.common.action.description.handler.impl;

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.List;

import com.onlyxiahui.common.action.description.DocumentContext;
import com.onlyxiahui.common.action.description.annotation.DocTitle;
import com.onlyxiahui.common.action.description.bean.MethodData;
import com.onlyxiahui.common.action.description.bean.ModuleData;
import com.onlyxiahui.common.action.description.bean.PropertyData;
import com.onlyxiahui.common.action.description.bean.ResultData;
import com.onlyxiahui.common.action.description.box.JsonDataTypeBox;
import com.onlyxiahui.common.action.description.enums.type.IgnorePropertyType;
import com.onlyxiahui.common.action.description.handler.PropertyHandler;
import com.onlyxiahui.common.action.description.handler.ResultHandler;
import com.onlyxiahui.common.action.description.util.ActionClassUtil;
import com.onlyxiahui.common.action.description.util.ActionDescriptionUtil;
import com.thoughtworks.qdox.model.JavaClass;

/**
 * Description <br>
 * Date 2020-01-07 16:17:59<br>
 * 
 * @author XiaHui [onlovexiahui@qq.com]<br>
 * @since 1.0.0
 */

public abstract class BaseResultHandler implements ResultHandler {

	/**
	 * <br>
	 * Date 2020-04-10 14:04:59<br>
	 * 
	 * @param context
	 * @param moduleData
	 * @param methodData
	 * @param method
	 * @return
	 * @since 1.0.0
	 */
	public ResultData create(DocumentContext context, ModuleData moduleData, MethodData methodData, Method method) {
		Class<?> returnClass = method.getReturnType();
		Type returnType = method.getGenericReturnType();

		if (void.class == returnClass) {
			return null;
		}

		String className = returnClass.getName();
		String description = getClassDescription(context, returnClass);
		String type = JsonDataTypeBox.getType(returnClass);

		ResultData md = new ResultData();

		md.setClassName(className);
		md.setType(type);
		md.setDescription(description);

		if (!ActionClassUtil.isPrimitive(returnClass)) {
			List<PropertyData> nodes = null;
			for (PropertyHandler ph : context.getPropertyHandlers()) {
				if (ph.support(context, returnClass, returnType)) {
					nodes = ph.handle(context, returnClass, returnType, IgnorePropertyType.result);
				}
			}
			md.setNodes(nodes);
		}
		return md;
	}

	public String getClassDescription(DocumentContext context, Class<?> beanClass) {
		String className = beanClass.getName();
		JavaClass jc = context.getSourceBox().getJavaClassByName(className);
		DocTitle docTitle = beanClass.getAnnotation(DocTitle.class);
		return ActionDescriptionUtil.getDescription(docTitle, jc);
	}
}
